package main;

import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import entity.Entity;
import math.Vector2D;
/**
 * 
 * @author Greg Giannone
 * 
 * This class is used to store all the entities and perform certain
 * operations on them
 *
 */

public class GameList
{
	private ArrayList<Entity> ents;
	
	public GameList()
	{
		ents = new ArrayList<Entity>();
	}
	public ArrayList<Entity> getList()
	{
		return ents;
	}
	public void add(Entity en)
	{
		ents.add(en);	
	}
	public Entity get(int i)
	{
		return ents.get(i);
	}
	public void remove(Entity e)
	{
		ents.remove(e);
	}
	/**
	 * See if an entity exists in the game list
	 * @param e
	 * @return
	 */
	public boolean contains(Entity e)
	{
		return ents.contains(e);
	}
	/**
	 * returns the closest entity of class c
	 */
	public <T extends Entity> T getClosest(Point2D pos, Class<T> c)
	{
		double dist = -1;
		int index = -1;
		for (int i = 0; i < ents.size(); i++)
		{
			Entity e = ents.get(i);
			
			double newDist = pos.distance(e.getPosition());
			if (c.isInstance(e) && (newDist <= dist || dist < 0))
			{
				dist = newDist;
				index = i;
			}
		}
		if (index >= 0)
			return (T)ents.get(index);
		return null;
	}
	
	public <T extends Object> ArrayList<T> getWithinRange(Point2D center, double range, Class<T> c)
	{
		ArrayList<T> entities = new ArrayList<T>();
		
		for (Entity e : ents)
		{
			if (e.isCircular())
			{
				//if the entity is circular, check based on the distance from center
				if (e.getPosition().distance(center) <= range && c.isInstance(e))
					entities.add((T)e);
			}
			else
			{
				//if the entity is not circular, see if object is within range based on rectangular bounds
				if (center.getX()+range > e.getPosition().getX() && center.getX()-range < e.getPosition().getX()+e.getWidth() &&
					center.getY()+range > e.getPosition().getY() && center.getY()-range < e.getPosition().getY()+e.getHeight() && c.isInstance(e))
					entities.add((T)e);
			}
					
		}
		
		return entities;
	}
	
	public void update(double duration)
	{
		Entity e;
		for(int i = 0; i < ents.size(); i++)
		{
			e = ents.get(i);
			e.update(duration);
		}
	}
	
	public void render(Graphics2D g)
	{
		for(Entity e : ents)
		{
			e.draw(g);
		}
	}
}
